/**
 * Created by xxx on 2017/7/6.
 */
var UE;
//父组件
var Main = React.createClass({
    //组件初始状态
    getInitialState: function () {
        return {
            otherData:[],
            addBanner:true,
            bannerSwitch: 1,//1:打开是否展示按钮 0：反之
            showImg:false,
            imgUrl:'',
            insideLink: false,
            bannerId: suixun.urlpara('bannerId'),
            updateImg: true,
            scrollTop:0,
        }
    },
    componentDidMount: function () {
        var svar = this;
        UE = suixun.editor();//初始化富文本
        if(svar.state.bannerId != ''){
            this.setState({addBanner:false});
            var param="param={";
            param = getJsonDataNotEmpty(param,"bannerId",""+svar.state.bannerId+"");
            param += "}";
            suixun.showLoding();//隐藏加载中
            suixun.ajax(serverUrl+'/banner/getBanner.json',param,"get",function(data){
                suixun.hideLoding();//隐藏加载中
                var insideLink = false;
                if(data.code == 200){
                    if(data.info.type == 2){
                        document.querySelector('#bannerUrl').value=data.info.content;//连接
                    }else{
                        insideLink = true;
                        UE.ready(function() {//编辑器初始化完成再赋值
                            UE.setContent(decodeURIComponent(data.info.content));  //赋值给UEditor
                        });
                    }
                    // document.querySelector('#file').value=data.info.content;//图片是否存在
                    document.querySelector('#bannerTitle').value=data.info.title;//主题摘要
                    $("#bannerRange").val(data.info.bannerRange==1?'家长端资讯主页':data.info.bannerRange==2?'教师端积分主页':'家长端积分主页');//banner类型
                    $(":radio[name='insideLink'][value='" + data.info.type + "']").prop("checked", "checked");
                    $(".msgType").val(data.info.index);//展示位置
                    document.querySelector('#bannerStateTime').value=data.info.startTime;//开始时间
                    document.querySelector('#bannerEndTime').value=data.info.endTime;//结束时间
                    svar.setState({bannerSwitch:data.info.isShow,showImg:true,updateImg:false,imgUrl:data.info.bannerUrl,insideLink:insideLink});
                }else{
                    suixun.alert(data.msg);
                }
            });
        }else{
            suixun.hideLoding();//显示加载中
        }
        this.getScroll();
    },
    /**
     * 动态监听滚动条
     */
    getScroll: function () {
        var svar = this;
        $(window).scroll(function(){
            var top = document.documentElement.scrollTop ? document.documentElement.scrollTop:document.body.scrollTop;
            svar.setState({scrollTop:top});
        });
    },
    /**
     * 链接样式切换
     * @returns {XML}
     */
    onClickRadio: function (type) {
        if(type == true){
            // suixun.alert('功能在开发中...',function (data) {
            //     if(data){
            //         $(":radio[name='insideLink'][value='2']").prop("checked", "checked");
            //     }
            // });
            this.setState({insideLink:type})
        }else{
            this.setState({insideLink:type})

        }
    },
    /**
     * 点击是否展示开关
     * @returns {XML}
     */
    onClickSwitch: function () {
        if(this.state.bannerSwitch == 0){
            this.setState({bannerSwitch:1})
        }else{
            this.setState({bannerSwitch:0})
        }
    },
    /**
     * 保存banner广告图
     */
    saveBanner: function () {
        var addBanner = this.state.addBanner,svar = this;
        var fileUrl = document.querySelector('#file').value;//图片是否存在
        var bannerTitle = document.querySelector('#bannerTitle').value;//主题摘要
        var bannerUrl = document.querySelector('#bannerUrl').value;//连接
        var bannerRange = $("#bannerRange").val();//bannner类型
        var content = UE.getContent();//获取编辑的内容
        var insideLink = $("input[name='insideLink']:checked").val();//获取值
        var msgType = document.querySelector('.msgType').value;//展示位置
        var bannerStateTime = document.querySelector('#bannerStateTime').value;//开始时间
        var bannerEndTime = document.querySelector('#bannerEndTime').value;//结束时间
        if(fileUrl=='' && !svar.state.showImg){
            suixun.alert('请选择图片！');
            return;
        }

        if(bannerTitle==''){
            suixun.alert('请填写主题摘要！');
            return;
        }
        if(insideLink == 2 && bannerUrl ==''){
            suixun.alert('请填写外部连接！');
            return;
        }else if(insideLink == 2 && bannerUrl.indexOf('http')==-1){
            suixun.alert('外部连接格式错误！');
            return;
        }else  if(insideLink == 1 && content ==''){
            suixun.alert('请填文章内容！');
            return;
        }else if(insideLink == 1 && content !=''){
            content = content.replace(/<table/g,'<div style="overflow: auto;  width: 100%;"><table');
            content = content.replace(/<\/table>/g,'<\/table><\/div>');
            bannerUrl = encodeURIComponent(content);
        }
        if((bannerStateTime =='' && bannerEndTime != '')||(bannerStateTime !='' && bannerEndTime == '')){
            suixun.alert('展示时间格式错误！');
            return;
        }else if((bannerStateTime !='' && bannerEndTime != '') && (new Date(bannerStateTime)>new Date(bannerEndTime))){
            suixun.alert('展示时间的开始时间不能大于结束时间！');
            return;
        }
        //先上穿图片
        if(addBanner){
            suixun.uploadImg('#file','',function (img) {
                var param="{";
                param = getJsonDataNotEmpty(param,"bannerUrl",'"'+img+'"');
                param = getJsonDataNotEmpty(param,"title",'"'+bannerTitle+'"');
                param = getJsonDataNotEmpty(param,"content",'"'+bannerUrl+'"');
                param = getJsonDataNotEmpty(param,"type",'"'+insideLink+'"');
                param = getJsonDataNotEmpty(param,"bannerRange",'"'+bannerRange+'"');
                param = getJsonDataNotEmpty(param,"index",'"'+msgType+'"');
                param = getJsonDataNotEmpty(param,"isShow",'"'+svar.state.bannerSwitch+'"');
                if(bannerStateTime != ''){
                    param = getJsonDataNotEmpty(param,"startTime",'"'+bannerStateTime+'"');
                    param = getJsonDataNotEmpty(param,"endTime",'"'+bannerEndTime+'"');
                }
                param += "}";
                var data = new FormData();
                data.append("param",param);
                suixun.showLoding();//显示加载中
                suixun.ajax(serverUrl+'/banner/addBanner.json',data,"post",function(data){
                    suixun.hideLoding();//隐藏加载中
                    if(data.code == 200){
                        suixun.alert('操作成功!');
                    }else{
                        suixun.alert(data.msg);
                    }
                });
            });
        }else{
            if(bannerRange == '家长端资讯主页'){
                bannerRange = '1';
            }else if(bannerRange == '教师端积分主页'){
                bannerRange = '2';
            }else{
                bannerRange = '3';
            }
            var param="{";
            if(svar.state.updateImg){
                suixun.uploadImg('#file','',function (img) {
                    param = getJsonDataNotEmpty(param,"bannerUrl",'"'+img+'"');
                    param = getJsonDataNotEmpty(param,"bannerId",'"'+svar.state.bannerId+'"');
                    param = getJsonDataNotEmpty(param,"title",'"'+bannerTitle+'"');
                    param = getJsonDataNotEmpty(param,"content",'"'+bannerUrl+'"');
                    param = getJsonDataNotEmpty(param,"type",'"'+insideLink+'"');
                    param = getJsonDataNotEmpty(param,"bannerRange",'"'+bannerRange+'"');
                    param = getJsonDataNotEmpty(param,"index",'"'+msgType+'"');
                    param = getJsonDataNotEmpty(param,"isShow",'"'+svar.state.bannerSwitch+'"');
                    if(bannerStateTime != ''){
                        param = getJsonDataNotEmpty(param,"startTime",'"'+bannerStateTime+'"');
                        param = getJsonDataNotEmpty(param,"endTime",'"'+bannerEndTime+'"');
                    }else{
                        param = getJsonDataNotEmpty(param,"startTime",'"1970-01-01 08:00:00"');
                        param = getJsonDataNotEmpty(param,"endTime",'"2999-01-01 08:00:00"');
                    }
                    param += "}";
                    var data = new FormData();
                    data.append("param",param);
                    suixun.showLoding();//显示加载中
                    suixun.ajax(serverUrl+'/banner/updateBanner.json',data,"post",function(data){
                        suixun.hideLoding();//隐藏加载中
                        if(data.code == 200){
                            suixun.alert('操作成功!');
                        }else{
                            suixun.alert(data.msg);
                        }
                    });
                });
            }else{
                // if(fileUrl != ''){
                //     param = getJsonDataNotEmpty(param,"bannerUrl",'"'+fileUrl+'"');
                // }
                param = getJsonDataNotEmpty(param,"bannerId",'"'+svar.state.bannerId+'"');
                param = getJsonDataNotEmpty(param,"title",'"'+bannerTitle+'"');
                param = getJsonDataNotEmpty(param,"content",'"'+bannerUrl+'"');
                param = getJsonDataNotEmpty(param,"type",'"'+insideLink+'"');
                param = getJsonDataNotEmpty(param,"index",'"'+msgType+'"');
                param = getJsonDataNotEmpty(param,"bannerRange",'"'+bannerRange+'"');
                param = getJsonDataNotEmpty(param,"isShow",'"'+svar.state.bannerSwitch+'"');
                if(bannerStateTime != ''){
                    param = getJsonDataNotEmpty(param,"startTime",'"'+bannerStateTime+'"');
                    param = getJsonDataNotEmpty(param,"endTime",'"'+bannerEndTime+'"');
                }else{
                    param = getJsonDataNotEmpty(param,"startTime",'"1970-01-01 08:00:00"');
                    param = getJsonDataNotEmpty(param,"endTime",'"2999-01-01 08:00:00"');
                }
                param += "}";
                var data = new FormData();
                data.append("param",param);
                suixun.showLoding();//显示加载中
                suixun.ajax(serverUrl+'/banner/updateBanner.json',data,"post",function(data){
                    suixun.hideLoding();//隐藏加载中
                    if(data.code == 200){
                        suixun.alert('操作成功!');
                    }else{
                        suixun.alert(data.msg);
                    }
                });
            }

        }

    },
    /**
     * 选择图片
     */
    onChangFile: function () {
        var svar = this;
        var fileUrl = $("#file").val().split('\\');//注split可以用字符或字符串分割
        var fileName = fileUrl[fileUrl.length-1];//这就是要取得的图片名称
        var fileLat = fileName.substring( fileName.lastIndexOf('.')+1 );//后缀名称
        if(fileLat == "png" || fileLat == "jpg" || fileLat == "gif" || fileLat == "svg"){
            var docObj = $("#file"),src ='';
            src = window.URL.createObjectURL(docObj[0].files[0]);
            // 图片地址 后面加时间戳是为了避免缓存
            var img_url = src;
            // 创建对象
            var img = new Image();
            // 改变图片的src
            img.src = img_url;
            // 加载完成执行
            img.onload = function(){
                // 打印
                // alert('width:'+img.width+',height:'+img.height);
                if((img.width==1125&&img.height==450)||(img.width==750&&img.height==300)){
                    svar.setState({showImg: true, imgUrl: src,updateImg:true});
                }else{
                    suixun.alert("图片大小错误！");
                }
            };
        }else{
            suixun.alert("请选择图片文件上传!",function (data) {
                if(data){
                    $("#file").val("");
                    svar.setState({showImg:false,imgUrl:''});
                }
            });
        }
    },
    /**
     * 加载图片
     * @returns {XML}
     */
    imgLoad: function () {
        new Viewer(document.querySelector('#showImg'));//调用图片
    },
    /**
     * 关闭图片
     * @returns {XML}
     */
    closeImg: function(){
        document.querySelector('#file').value = '';
        this.setState({showImg:false,imgUrl:'',updateImg:true});
    },
    render: function () {
        return (
            <div className="tableManage-body" style={{paddingBottom:"140px"}}>
                <header>
                    <div>&nbsp;&nbsp;&nbsp;&nbsp;{this.state.addBanner==true?'新增':'编辑'}banner图</div>
                </header>
                <div className="addBanner-bannerBody">
                    <div className="addBanner-bannerBody-content">
                        <div className="addBanner-bannerBody-content-title" style={{backgroundPosition: '64px 3px'}}>banner图</div>
                        <div className="addBanner-bannerBody-content-text">
                            <form name="excelInputForm" id="excelInputFrom" method="post">
                                <input type="hidden" className="input-fileImg" name="filename"  />
                                    <a href="javascript:;" className="file">
                                        上传图片
                                        <input type="file" onChange={this.onChangFile.bind(this)} name="file" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" id="file" />
                                    </a>
                            </form>
                            {
                                this.state.showImg==true?
                                    <div className="uploadShowImg">
                                        <span onClick={this.closeImg.bind(this)}/>
                                        <lable><img onLoad={this.imgLoad.bind(this)} src={this.state.imgUrl} id="showImg"  /></lable>
                                    </div>:''
                            }
                            <span className="inputFile-remarks">图片规格：1125像素*450像素或750像素*300像素</span>
                        </div>
                    </div>
                    <div className="addBanner-bannerBody-content">
                        <div className="addBanner-bannerBody-content-title">主题摘要</div>
                        <div className="addBanner-bannerBody-content-text">
                            <div className="content-border">
                                <input type="text" id="bannerTitle" className="input-content" placeholder="请填写主题摘要" maxLength="200"/>
                            </div>
                        </div>
                    </div>
                    <div className="addBanner-bannerBody-content">
                        <div className="addBanner-bannerBody-content-title">链接样式</div>
                        <div className="addBanner-bannerBody-content-text">
                            <label className="radio-content "><input name="insideLink" value="2" type="radio" checked={this.state.insideLink == false?'checked':''} onClick={this.onClickRadio.bind(this,false)}/><span>外部链接展示</span></label>
                            <label className="radio-content external-link"><input name="insideLink" value="1" type="radio" checked={this.state.insideLink == true?'checked':''} onClick={this.onClickRadio.bind(this,true)}/><span>内容编辑展示</span></label>
                        </div>
                    </div>
                    <div className="addBanner-bannerBody-content" style={{display:this.state.insideLink == true?'block':'none'}}>
                        <div className="addBanner-bannerBody-content-title">内容编辑</div>
                        <div className="addBanner-bannerBody-content-text" style={{marginBottom:"20px"}}>
                            <script id="editor" type="text/plain" />
                        </div>
                    </div>
                    <div className="addBanner-bannerBody-content" style={{display:this.state.insideLink == true?'none':'block'}}>
                        <div className="addBanner-bannerBody-content-title">{this.state.insideLink == false?'添加链接':'内容编辑'}</div>
                        <div className="addBanner-bannerBody-content-text">
                            <div className="content-border">
                                <input type="text" id="bannerUrl" className="input-content" placeholder="请填写外部链接" maxLength="200" />
                            </div>
                        </div>
                    </div>
                    <div className="addBanner-bannerBody-content">
                        <div className="addBanner-bannerBody-content-title" >是否展示</div>
                        <div className="addBanner-bannerBody-content-text">
                            <div className={this.state.bannerSwitch==1?'widget switch checked':'widget switch '} >
                                <div className="wrapper"></div>
                                <div className="circle" onClick={this.onClickSwitch}></div>
                            </div>
                        </div>
                    </div>
                    <div className="addBanner-bannerBody-content">
                        <div className="addBanner-bannerBody-content-title">展示位置</div>
                        <div className="addBanner-bannerBody-content-text">
                            <div className="content-select-border">
                                <select className="export-factory msgType pop-select" >
                                    <option value="1" selected="selected" >第一张</option>
                                    <option value="2" >第二张</option>
                                    <option value="3" >第三张</option>
                                    <option value="4" >第四张</option>
                                    <option value="5" >第五张</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    {
                        this.state.bannerId != ''?
                                <div className="body-content">
                                    <div className="body-content-title" style={{backgroundPosition: '75px 3px'}}>banner类型</div>
                                    <div className="body-content-text">
                                        <div className="content-border element-content noBorder textInput" > <input type="text" id="bannerRange"/></div>
                                    </div>
                                </div>
                                :
                            <div className="addBanner-bannerBody-content">
                                <div className="addBanner-bannerBody-content-title" style={{width:'110px',backgroundPosition:'75px 4px'}}>banner类型</div>
                                <div className="addBanner-bannerBody-content-text">
                                    <div className="content-select-border">
                                        <select className="export-factory pop-select" id="bannerRange">
                                            <option value="1" selected="selected" >家长端资讯主页</option>
                                            <option value="2" >教师端积分主页</option>
                                            <option value="3" >家长端积分主页</option>
                                        </select>
                                    </div>
                                </div>
                            </div>


                    }


                    <div className="addBanner-bannerBody-content">
                        <div className="addBanner-bannerBody-content-title" style={{backgroundImage: 'url("")'}}>定时展示</div>
                        <div className="addBanner-bannerBody-content-text">
                            <div className="content-border" style={{width:'180px'}}>
                                <input type="text" className="input-content input-time" id="bannerStateTime" placeholder="请选择开始时间" maxLength="50" />
                            </div>
                            <span className="addBanner-line"/>
                            <div className="content-border" style={{width:'180px'}}>
                                <input type="text" className="input-content input-time" id="bannerEndTime"  placeholder="请选择结束时间" maxLength="50" />
                            </div>
                        </div>
                    </div>
                    <div className="addBanner-foot" style={this.state.insideLink == false?{top:'600px',left:'345px'}:this.state.scrollTop>=290?{top:'0px'}:{top:290-this.state.scrollTop+'px'}}>
                        <span className="foot-button button-save" onClick={this.saveBanner.bind(this)}>保存</span>
                        <span className="foot-button button-preview" style={{display:this.state.insideLink == true?'block':'none'}}>预览</span>
                    </div>
                </div>
                <div className="preview-layer">
                    <div className="preview-bg"/>
                    <img src="../img/icon/close_white.png" title="关闭"  className="preview_img close"  />
                    <div className="preview-phone">
                        <iframe id="preview-html" name="preview-html" src="../ueditor/preview-h5.html"/>
                    </div>
                </div>
                <footer id="copyright">
                    <span><img src="../img/icon/copyright.png"/>{copyright}</span>
                </footer>
            </div>
        );
    }
});
ReactDOM.render(
    <Main />,
    document.getElementById('tableManage')
);
$('.input-time').datetimepicker({
    format: "Y-m-d H:i:s", //格式化日期
    timepicker: true, //显示时间选项
    todayButton: false, //关闭选择今天按钮
    step:1,//时间间隔
    // minDate:suixun.getFormatDate(), // and tommorow is maximum date calendar
});